var speedCanvas;
var speedContext;
var UpgrRadios;
var CreepRadios;
var BurrRadios;
var StimRadios;
var AirRadios;
var TEnabled;
var PEnabled;
var ZEnabled;
var ChartWidth = 600;
var ChartBuffer = 40; // buffer to the left and right of the chart
var BarHeight = 20;

var TColor = "#ee0000";
var PColor = "#eeee00";
var ZColor = "#ee00ee";

var ChartOutput = [""];

function initialize()
{
	speedCanvas = document.getElementById("speedchart");
	UpgrRadios = document.getElementsByName('upgrades');
	CreepRadios = document.getElementsByName('creep');
	BurrRadios = document.getElementsByName('burrow');
	StimRadios = document.getElementsByName('stim');
	AirRadios = document.getElementsByName('air');
	debugBox = document.getElementById("DebugBox");	
	debugBox2 = document.getElementById("DebugBox2");	
	speedContext = speedCanvas.getContext("2d");
	
	speedContext.canvas.width = ChartWidth;
	speedContext.canvas.height = 1180;  // TODO: remove hard-coded height
	
	
	TEnabled = document.getElementById("enableTerran");
	PEnabled = document.getElementById("enableProtoss");
	ZEnabled = document.getElementById("enableZerg");
	AirOnlyRadio = document.getElementById("showAirOnly");
	TEnabled.addEventListener("click",redrawChart,false);
	PEnabled.addEventListener("click",redrawChart,false);
	ZEnabled.addEventListener("click",redrawChart,false);
	UpgrRadios[0].addEventListener("click",redrawChart,false);
	UpgrRadios[1].addEventListener("click",redrawChart,false);
	UpgrRadios[2].addEventListener("click",redrawChart,false);
	CreepRadios[0].addEventListener("click",redrawChart,false);
	CreepRadios[1].addEventListener("click",redrawChart,false);
	CreepRadios[2].addEventListener("click",redrawChart,false);	
	BurrRadios[0].addEventListener("click",redrawChart,false);
	BurrRadios[1].addEventListener("click",redrawChart,false);
	BurrRadios[2].addEventListener("click",redrawChart,false);	
	StimRadios[0].addEventListener("click",redrawChart,false);
	StimRadios[1].addEventListener("click",redrawChart,false);
	StimRadios[2].addEventListener("click",redrawChart,false);	
	AirRadios[0].addEventListener("click",redrawChart,false);
	AirRadios[1].addEventListener("click",redrawChart,false);
	AirRadios[2].addEventListener("click",redrawChart,false);	
		
	redrawChart();
}

function removeElement(inArray, i)
{
	// This is a simple, slow way to delete elements. I'll replace it if necessary.
	//debugBox.value += "Trying to remove: " + inArray[i].UnitName + " " + inArray[i].Speed + "\t" + inArray[i].Upgraded + "\n";
	inArray = inArray.slice(0,i).concat(inArray.slice(i+1) );
	return inArray;
}

function redrawChart()
{
	debugBox.value = "";
	debugBox2.value = "";
	// reset ChartOutput to nil
	ChartOutput = [];
	var sortedOutput = [];
    
	// if box is checked, include Terran in what to render, etc
	if (TEnabled.checked)
	{
		document.getElementById("terranOptions").style.display = "block";
		for (sCount = 0; sCount < SpeedArray.length;sCount++)
		{
			if (SpeedArray[sCount].Race == "T")
			{
				ChartOutput[ChartOutput.length] = SpeedArray[sCount];	
			}
		}
	} else // hide the Stim options if we won't be showing Terran units
	{ document.getElementById("terranOptions").style.display = "none"; }
	if (ZEnabled.checked)
	{		
		document.getElementById("zergOptions").style.display = "block";
		for (sCount = 0; sCount < SpeedArray.length;sCount++)
		{
			if (SpeedArray[sCount].Race == "Z")
			{
				ChartOutput[ChartOutput.length] = SpeedArray[sCount];	
			}
		}
	} else // hide the Burrow/Creep options if we aren't showing Zerg units
	{ document.getElementById("zergOptions").style.display = "none"; }
	if (PEnabled.checked)
	{
		for (sCount = 0; sCount < SpeedArray.length;sCount++)
		{
			if (SpeedArray[sCount].Race == "P")
			{
				ChartOutput[ChartOutput.length] = SpeedArray[sCount];	
			}
		}
	}
	// if showAirOnly is enabled, hide terranOptions and zergOptions
	if (AirOnlyRadio.checked)
	{
		document.getElementById("terranOptions").style.display = "none"; 
		document.getElementById("zergOptions").style.display = "none";
			
	}

	// filter on Upgrades
	// 	0 -- unit has only one speed
	// 	1 -- unit has an upgrade. This is the upgrade speed
	// 	2 -- unit has an upgrade. This is the base speed
	// 	Show base speed only --> (exclude 1s)
	// 	Upgrade if possible  --> (exclude 2s)
	// 	Show both            --> (exclude none)
	if (!UpgrRadios[2].checked)
	{
		var uExcluded;
		if (UpgrRadios[0].checked) { uExcluded = "1";} else { uExcluded = "2";}
		for (fCount = 0; fCount < ChartOutput.length; fCount++)
		{
			if (ChartOutput[fCount].Upgraded == uExcluded)
			{
				ChartOutput = removeElement(ChartOutput, fCount);
				fCount--; // The returned array has been shortened, so we need to recheck this element
			}
		}
	} 

	// filter Creep
 	if (!CreepRadios[2].checked) // don't filter anything if "both" is checked
 	{
 		var cExcluded;
 		if (CreepRadios[0].checked) {cExcluded = "1";} else {cExcluded = "2";} 
  		for (cCount = 0; cCount < ChartOutput.length; cCount++)
		{
			if ((ChartOutput[cCount].Race == "Z") && (ChartOutput[cCount].OnCreep == cExcluded) )
			{
			ChartOutput = removeElement(ChartOutput, cCount);
			cCount--;
			}
		}
  	}
  	
	// filter on Burrow
	if (!BurrRadios[2].checked)
	{
		var bExcluded;
		if (BurrRadios[0].checked) {bExcluded = "1";} else {bExcluded = "2";}
		for (bCount = 0; bCount < ChartOutput.length; bCount++)
		{
			if ((ChartOutput[bCount].Race == "Z") && (ChartOutput[bCount].Burrowed == bExcluded))
			{
			ChartOutput = removeElement(ChartOutput, bCount);
			bCount--;
			}
		}
	}
	
	// filter on Stim
	if (!StimRadios[2].checked)
	{
		var sExcluded;
		if (StimRadios[0].checked) {sExcluded = "1";} else {sExcluded = "2";}
		for (sCount = 0; sCount < ChartOutput.length; sCount++)
		{
			if ((ChartOutput[sCount].Race == "T") && (ChartOutput[sCount].Stimmed == sExcluded))
			{
			ChartOutput = removeElement(ChartOutput, sCount);
			sCount--;	
			}	
		}	
	}
	
	// filter on Air
	if (!AirRadios[2].checked)
	{
		var aExcluded;
		if (AirRadios[0].checked) {aExcluded ="1";} else {aExcluded = "0";}
		for (aCount = 0; aCount < ChartOutput.length; aCount++)
		{
			if (ChartOutput[aCount].IsAir == aExcluded)	
			{
				ChartOutput = removeElement(ChartOutput, aCount);
				aCount--;
			}		
		}	
	}
  	
  	sortedOutput = ChartOutput.sort(compareSpeeds);
	// now Draw
	// First, wipe out the whole Canvas:	
	var iconSpace = Math.round(BarHeight*1.17);
	var cHeight = ChartOutput.length * iconSpace + 100;
	speedContext.canvas.height = cHeight;
	speedContext.fillStyle="#555555";
	speedContext.fillRect(0,0,ChartWidth,cHeight);  // TODO: remove hard-coded canvas height 
	
	var maxSpeed = 0;
	// The bars should reach most of the way across the canvas. Find the highest remaining speed:
	for (var x = 0; x < sortedOutput.length; x++)
	{
		if (sortedOutput[x].Speed > maxSpeed) { maxSpeed = sortedOutput[x].Speed; }
	}
	
	// Buffer - Text - Icons - ChartBar - Buffer
	// 40		80		80		??			40
	var iconBlock = 5*iconSpace // one slot each for upgrades, creep, burrow, stim, Icon
	var textBlock = 72 // the space taken up by the unit name. Hard-coded for now.
	debugBox.value += "STARTING. sortedOutput.length is " + sortedOutput.length + "\n";
	for (var x = 0; x < sortedOutput.length; x++)
		{
			// Draw the unit icon 
			var unitIconObj = new Image();
			if (sortedOutput[x].Filename == "--") // I don't have real icons for a few units
			{
				unitIconObj.src = "Icons/Creep.jpg";	
			} else 
			{
				unitIconObj.src = "Icons/" + sortedOutput[x].Filename + ".jpg";
			}
			speedContext.drawImage(unitIconObj, ChartBuffer+textBlock+2+4*iconSpace, 50+(x*iconSpace), BarHeight, BarHeight);
			debugBox.value +="At " + x + ", drawing: " + sortedOutput[x].Filename + "\n";
			// Draw the speed bar.
			if (sortedOutput[x].Race == "T")
			{speedContext.fillStyle=TColor;}
			if (sortedOutput[x].Race == "P")
			{speedContext.fillStyle=PColor;}
			if (sortedOutput[x].Race == "Z")
			{speedContext.fillStyle=ZColor;}
			// syntax here is: speedContext.fillRect(startx, starty, xwidth, ywidth) 
			speedContext.fillRect(ChartBuffer+textBlock+iconBlock, 50+iconSpace*x, sortedOutput[x].Speed*(ChartWidth - 2*ChartBuffer - iconBlock-textBlock)/maxSpeed, BarHeight);
			// at 12 height, I used 16px font. At 20 height... xxx looks good.
			speedContext.font = "bold 20px Calibri";
			speedContext.textAlign = "left";
			// draw the unit speed on the bar
			var speedTextBuffer = 2; // this looks about right.
			speedContext.fillStyle="#cccccc";
			speedContext.fillText(sortedOutput[x].Speed, ChartBuffer+textBlock+iconBlock + speedTextBuffer + 1, 61+5+(iconSpace*x)+1);		
			speedContext.fillStyle="#000000";
			speedContext.fillText(sortedOutput[x].Speed, ChartBuffer+textBlock+iconBlock + speedTextBuffer, 61+5+(iconSpace*x));
			speedContext.font = "bold 12px Calibri";
			var upgrStatus = 0;
			var creepStatus = 0;
			var burrStatus = 0;
			var stimStatus = 0;
			var upgObj = new Image();
			upgObj.src = "Icons/Upgrade.jpg";
			var creepObj = new Image();
			creepObj.src = "Icons/Creep.jpg";
			var burrObj = new Image();
			burrObj.src = "Icons/Burrow.jpg";
			var stimObj = new Image();
			stimObj.src = "Icons/Stim.jpg";
			if (sortedOutput[x].Upgraded == "1") 
			{
				upgrStatus= 1;
				speedContext.drawImage(upgObj, ChartBuffer+textBlock+2, 50+(x*iconSpace), BarHeight, BarHeight);
			}
			if (sortedOutput[x].OnCreep == "1") 
			{	creepStatus= 1;
				speedContext.drawImage(creepObj, ChartBuffer+textBlock+2+iconSpace, 50+(x*iconSpace), BarHeight, BarHeight);
			}
			if (sortedOutput[x].Burrowed == "1") 
			{
				burrStatus= 1;
				speedContext.drawImage(burrObj, ChartBuffer+textBlock+2+2*iconSpace, 50+(x*iconSpace), BarHeight, BarHeight);
			}
			if (sortedOutput[x].Stimmed == "1") 
			{
				stimStatus= 1;
				speedContext.drawImage(stimObj, ChartBuffer+textBlock+2+3*iconSpace, 50+(x*iconSpace), BarHeight, BarHeight);
			}
			// Write the unit name	
			speedContext.fillStyle="#000000";
			speedContext.textAlign = "right";
			speedContext.fillText(sortedOutput[x].UnitName, ChartBuffer+textBlock + 1, 65+(x*iconSpace));
			speedContext.fillStyle="#cccccc";
			speedContext.textAlign = "right";
			speedContext.fillText(sortedOutput[x].UnitName, ChartBuffer+textBlock, 64+(x*iconSpace));
		}
}

function compareSpeeds(a,b)
{
	return a.Speed-b.Speed;
}